<template>
  <el-space
    size="large"
    direction="vertical"
    style="width: 100%"
    alignment="flex-start"
    fill
  >
    <!-- 项目简介 -->
    <div v-if="detailData.acceptApplyRespVO" class="project-title">
      <div class="item">
        <span class="label">项目验收申请ID：</span>
        <span>{{ detailData.acceptApplyRespVO.id }}</span>
      </div>
      <div class="item">
        <span class="label">审核状态：</span>
        <span>
          {{
            dictStore.getDictLabelForValue(
              'audit_status',
              detailData.acceptApplyRespVO.status
            )
          }}
        </span>
      </div>
      <div class="item">
        <span class="label">记录创建人：</span>
        <span>{{ detailData.acceptApplyRespVO.creatorName }}</span>
      </div>
      <div class="item">
        <span class="label">记录创建时间：</span>
        <span>
          {{
            $XEUtils.toDateString(
              detailData.acceptApplyRespVO.createTime,
              'yyyy-MM-dd HH:mm:ss'
            )
          }}
        </span>
      </div>
    </div>
    <!-- 项目简介 -->
    <!-- 项目信息 -->
    <div v-if="detailData.projectInfo" class="box" style="width: 100%">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon2.png" alt="" class="icon" />
          <span>项目信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData.projectInfo]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="projectCode" title="项目编号" />
          <vxe-column field="projectName" title="项目名称" />
          <vxe-column field="projectLevel" title="项目级别">
            <template #default="{ row }">
              {{
                dictStore.getDictLabelForValue(
                  'project_level',
                  row.projectLevel
                )
              }}
            </template>
          </vxe-column>
          <vxe-column field="projectTypeName" title="项目类型" />
          <vxe-column field="keyProject" title="是否重点项目">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('yes_no', row.keyProject) }}
            </template>
          </vxe-column>
          <vxe-column field="headerName" title="项目负责人" />
        </vxe-table>
      </el-space>
    </div>
    <!-- 项目信息 -->
    <!-- 课题信息 -->
    <div v-if="detailData.topicInfo" class="box">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon2.png" alt="" class="icon" />
          <span>课题信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData.topicInfo]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="id" title="课题编号" />
          <vxe-column field="name" title="课程名称" />
          <vxe-column field="leader" title="课题负责人" />
          <vxe-column field="type" title="课题类型">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('topic_type', row.type) }}
            </template>
          </vxe-column>
          <vxe-column field="subjectAreaText" title="专业领域" />
          <vxe-column
            field="researchStartDate"
            title="研究开始时间"
            :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
          />
          <vxe-column
            field="researchEndDate"
            title="研究结束时间"
            :formatter="['formatDate', 'yyyy-MM-dd HH:mm:ss']"
          />
          <vxe-column field="estimatedBudget" title="预计投入经费（万元）" />
          <vxe-column field="externalCooperationRequired" title="是否需要外协">
            <template #default="{ row }">
              {{
                dictStore.getDictLabelForValue(
                  'yes_no',
                  row.externalCooperationRequired
                )
              }}
            </template>
          </vxe-column>
          <vxe-column field="leadingUnitName" title="承担单位" />
          <vxe-column field="collaboratingUnitNames" title="协作单位" />
        </vxe-table>
      </el-space>
    </div>
    <!-- 课题信息 -->
    <!-- 其他信息 -->
    <div v-if="detailData.acceptApplyRespVO" class="box">
      <el-space
        size="large"
        direction="vertical"
        style="width: 100%"
        alignment="flex-start"
        fill
      >
        <div class="common-title">
          <img src="@/assets/project_images/icon4.png" alt="" class="icon" />
          <span>其他信息</span>
        </div>
        <vxe-table
          align="left"
          :data="[detailData.acceptApplyRespVO]"
          size="small"
          border
          min-height="0"
        >
          <vxe-column field="type" title="验收类型">
            <template #default="{ row }">
              {{ dictStore.getDictLabelForValue('accept_type', row.status) }}
            </template>
          </vxe-column>
        </vxe-table>
      </el-space>
    </div>
    <!-- 其他信息 -->
  </el-space>

  <el-form
    ref="ruleFormRef"
    style="max-width: 800px; margin-top: 40px"
    :model="ruleForm"
    :rules="rules"
  >
    <el-form-item label="验收材料：" />
    <el-form-item label="验收申请表:" prop="16">
      <el-upload
        v-model:file-list="ruleForm['16']"
        :http-request="(options) => customUpload(options, '16')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="研究大纲:" prop="17">
      <el-upload
        v-model:file-list="ruleForm['17']"
        :http-request="(options) => customUpload(options, '17')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="计划任务书:" prop="18">
      <el-upload
        v-model:file-list="ruleForm['18']"
        :http-request="(options) => customUpload(options, '18')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="研究报告:" prop="19">
      <el-upload
        v-model:file-list="ruleForm['19']"
        :http-request="(options) => customUpload(options, '19')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="财务决算报告:" prop="20">
      <el-upload
        v-model:file-list="ruleForm['20']"
        :http-request="(options) => customUpload(options, '20')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="经济及社会效益分析报告:" prop="21">
      <el-upload
        v-model:file-list="ruleForm['21']"
        :http-request="(options) => customUpload(options, '21')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="用户使用报告:" prop="22">
      <el-upload
        v-model:file-list="ruleForm['22']"
        :http-request="(options) => customUpload(options, '22')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="标准化审查报告:" prop="23">
      <el-upload
        v-model:file-list="ruleForm['23']"
        :http-request="(options) => customUpload(options, '23')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="知识产权报告:" prop="24">
      <el-upload
        v-model:file-list="ruleForm['24']"
        :http-request="(options) => customUpload(options, '24')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="自验收结论报告:" prop="25">
      <el-upload
        v-model:file-list="ruleForm['25']"
        :http-request="(options) => customUpload(options, '25')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
    <el-form-item label="验收评价报告:" prop="26">
      <el-upload
        v-model:file-list="ruleForm['26']"
        :http-request="(options) => customUpload(options, '26')"
        :before-upload="beforeUpload"
        :on-remove="handleRemove"
        style="min-width: 100%"
      >
        <el-button type="primary" plain>
          <el-icon class="el-icon--left"><Upload /></el-icon>
          上传
        </el-button>
      </el-upload>
    </el-form-item>
  </el-form>

  <commonFooterBar>
    <!--<el-button :loading="loading" @click="submitForm(ruleFormRef)">
      保存为草稿
    </el-button>-->
    <el-button
      type="primary"
      :loading="loading"
      @click="submitForm(ruleFormRef, 2)"
    >
      确认提交
    </el-button>
  </commonFooterBar>
</template>

<script setup>
  import { useDictStore } from '@/store/modules/dict'
  import { postActionUpload } from '@/api/requestEvents'
  import commonFooterBar from '@/components/commonFooterBar.vue'
  import {
    acceptApplyUploadFile,
    acceptApplyGet,
  } from '@/api/project/accept/task-in'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { postDraftBoxCreate } from '@/api/project/drafts'

  const { closeTabNavigate } = useCloseTabNavigate()

  const $baseMessage = inject('$baseMessage')
  const dictStore = useDictStore()
  const route = useRoute()

  const detailData = ref({})

  const ruleFormRef = ref()
  const ruleForm = reactive({})
  const rules = reactive({
    16: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    17: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    18: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    19: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    20: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    21: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    22: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    23: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    24: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    25: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
    26: [
      {
        required: true,
        message: '请上传文件',
        trigger: 'change',
      },
    ],
  })

  const loading = ref(false)

  //初始化数据
  const initFormData = (id, getType = 2) => {
    acceptApplyGet({
      id: id,
      getType,
    }).then((res) => {
      if (res.code == 0 || res.code == 200) {
        if (getType == 1) {
          setFormData(res.data?.relatedDocumentList)
          initFormData(res.data.acceptApplyId, 2)
        } else {
          detailData.value = res.data || {}
          route.query.getType == 2 &&
            setFormData(res.data?.acceptApplyRespVO?.relatedDocumentList || [])
        }
      }
    })
  }

  const setFormData = (data) => {
    data.forEach((item) => {
      if (!ruleForm[item.fileBusinessType]) {
        ruleForm[item.fileBusinessType] = []
      }
      ruleForm[item.fileBusinessType].push({
        uid: item.fileId,
        name: item.fileName,
        url: item.fileUrl,
        id: item.fileId,
        type: item.fileType,
      })
    })
  }

  // 文件上传前的检查
  const beforeUpload = (file) => {
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      ElMessage.error('上传文件大小不能超过 5MB!')
    }
    return isLt5M
  }

  const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles)
  }

  // 文件自定义上传
  const customUpload = async (options, key) => {
    const formData = new FormData()
    formData.append('file', options.file)
    try {
      // 调用 getFileUploadReturn 接口获取上传文件的返回信息
      const resUpload = await postActionUpload(
        '/infra/file/upload-return-obj',
        formData,
        options
      )
      if (resUpload.code === 0 && resUpload.data) {
        const fileItem = ruleForm[key].find(
          (item) => item.uid === options.file.uid
        )
        if (fileItem) {
          fileItem.name = resUpload.data.name
          fileItem.url = resUpload.data.url
          fileItem.id = resUpload.data.id
          fileItem.type = resUpload.data.type
        }

        ElMessage.success('文件上传成功')
      } else {
        ruleForm[key] = ruleForm[key].filter(
          (item) => item.uid !== options.file.uid
        )
      }
    } catch (error) {
      ElMessage.error('文件上传失败')
      console.error('文件上传失败', error)
      ruleForm[key] = ruleForm[key].filter(
        (item) => item.uid !== options.file.uid
      )
    }
  }

  //表单提交
  const submitForm = async (formEl, type = 1) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        let relatedDocumentList = []
        for (const key in ruleForm) {
          const arr = ruleForm[key].map((item) => {
            return {
              fileBusinessType: key,
              fileName: item.name,
              fileType: item.type,
              fileId: item.id,
              fileUrl: item.url,
            }
          })
          relatedDocumentList = relatedDocumentList.concat(arr)
        }
        const params = {
          id: detailData.value.acceptApplyRespVO?.id,
          relatedDocumentList,
        }

        loading.value = true

        if (type == 2) {
          const api =
            route.query.id && route.query?.getType == 2
              ? acceptApplyUploadFile
              : acceptApplyUploadFile
          if (route.query?.getType == 1) {
            params.draftBoxId = route.query.id
          }
          api(params)
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                $baseMessage('上传成功')
                closeTabNavigate()
              }
            })
            .finally(() => {
              loading.value = false
            })
        } else {
          const formData = {
            id: route.query?.getType == 1 ? route.query.id : '',
            type: 'PROJECT_ACCEPT_RESULT',
            submitJson: JSON.stringify({
              ...params,
              acceptApplyId: detailData.value.acceptApplyRespVO.id,
              draftBoxId: route.query?.getType == 1 ? route.query.id : '',
            }),
          }

          postDraftBoxCreate(formData)
            .then((res) => {
              if (res.code == 0 || res.code == 200) {
                $baseMessage('保存草稿成功')
                closeTabNavigate()
              }
            })
            .finally(() => {
              loading.value = false
            })
        }
      }
    })
  }
  initFormData(route.query.id, route.query.getType)
</script>

<style lang="scss" scoped>
  .project-title {
    display: flex;
    align-items: center;
    width: 100%;
    min-height: 28px;
    padding: 10px;
    background: var(--vxe-table-header-background-color);

    .item {
      display: inline-flex;
      margin-right: 90px;
      font-size: $base-font-size-default;

      .label {
        color: $base-color-text-secondary;
      }
    }
  }

  .box {
    .common-title {
      display: flex;
      align-items: center;
      font-size: $base-font-size-default;
      font-weight: bold;
      color: $base-color-text-primary;

      .icon {
        margin-right: 10px;
      }
    }

    .sub-title {
      font-size: $base-font-size-small;
      font-weight: bold;
    }
  }
</style>
